<?php
// +----------------------------------------------------------------------
// | ThinkBLOG (Build on ThinkPHP)
// +----------------------------------------------------------------------
// | @link ( http://www.yurnero.net )
// +----------------------------------------------------------------------
// | @licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | @author nicholas <nicholasinlove@126.com>
// +----------------------------------------------------------------------
// | $Id: OptionsModel.class.php 106 2012-04-06 08:38:14Z nicholasinlove1986@gmail.com $
// +----------------------------------------------------------------------


class OptionsModel extends AdvModel {
	
	/**
	 * 
	 * 字段信息
	 * 
	 * @var Model
	 */
	protected $fields = array (0 => 'name', 1 => 'user', 2 => 'value', '_autoinc' => false, '_pk' => 'user', '_type' => array ('name' => 'varchar(32)', 'user' => 'int(10) unsigned', 'value' => 'text' ) );
	
	/**
	 * 获取选项值
	 *
	 * @access public
	 * @param $name 选项名
	 * 
	 * @return mix
	 */
	public function getOptions($name = NULL) {
		if (empty ( $name )) {
			$data = $this->select ();
			foreach ( $data as $key => $row ) {
				$data [$row ['name']] = $row ['value'];
				unset ( $data [$key] );
			}
			return $data;
		} else {
			return $this->where ( "name = '$name'" )->getField ( 'value' );
		}
	}
	
	/**
	 * 设置选项值
	 *
	 * @access public
	 * @param $data 数组
	 * 
	 * @return void
	 */
	public function setOptions($data) {
		
		if (! $data || ! is_array ( $data )) {
			return false;
		}
		$status = false;
		foreach ( $data as $key => $value ) {
			
			$status = $this->where ( "name = '{$key}'" )->setField ( 'value', trim ( $value ) );
			if ($status === false) {
				break;
			}
		}
		
		if ($status !== false) {
			S ( 'options', NULL );
		}
		return $status;
	
	}
	
	/**
	 * 添加选项值
	 *
	 * @param $name 选项名
	 * @param $value 选项值
	 *
	 * @return bool
	 */
	public function addOptions($name, $value) {
		if ($this->getOptions ( $name ) !== NULL) {
			return false;
		}
		$data ['name'] = $name;
		$data ['user'] = 0;
		$data ['value'] = $value;
		return $this->add ( $data );
	}
	
	/**
	 * 删除选项值
	 *
	 * @param $name 选项名
	 *
	 * @return void
	 */
	public function delOptions($name) {
		return $this->where ( "name = '$name'" )->delete ();
	}

}